import Url from "url-parse";
import qs from "qs";

let myHelper = {};

myHelper.checkIsDataURI = function (dataURI) {
    return dataURI.split(",")[0].indexOf("base64") >= 0;
};
myHelper.dataURItoBlob = function (dataURI) {
    // convert base64 to raw binary data held in a string

    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    let byteString;
    if (dataURI.split(",")[0].indexOf("base64") >= 0) {
        byteString = atob(dataURI.split(",")[1]);
    } else {
        byteString = unescape(dataURI.split(",")[1]);
    }

    // separate out the mime component

    let mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];

    // write the bytes of the string to an ArrayBuffer

    let ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer

    let ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values

    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done

    let blob = new Blob([ab], { type: mimeString });
    return blob;
};
myHelper.dataURItoFile = function (dataURI, filename, lastModified) {
    // convert base64 to raw binary data held in a string

    // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
    let byteString;
    if (dataURI.split(",")[0].indexOf("base64") >= 0) {
        byteString = atob(dataURI.split(",")[1]);
    } else {
        byteString = unescape(dataURI.split(",")[1]);
    }

    // separate out the mime component

    let mimeString = dataURI
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
    if (!lastModified) {
        lastModified = Date.now();
    }
    if (!filename) {
        let ext = mimeString.split("/")[1] || "bin";
        filename = `upload.${ext}`;
    }
    // write the bytes of the string to an ArrayBuffer

    let ab = new ArrayBuffer(byteString.length);

    // create a view into the buffer

    let ia = new Uint8Array(ab);

    // set the bytes of the buffer to the correct values

    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // write the ArrayBuffer to a blob, and you're done

    let file = new File([ab], filename, {
        type: mimeString,
        lastModified: lastModified
    });
    return file;
};
myHelper.getBase64ImageFromUrl = async function (imageUrl) {
    let res = await fetch(imageUrl);
    let blob = await res.blob();
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.addEventListener(
            "load",
            function () {
                resolve(reader.result);
            },
            false
        );
        reader.onerror = () => {
            return reject(this);
        };
        reader.readAsDataURL(blob);
    }).catch((e) => {
        console.log(e,'e1')
    });
};

/**
 * host片段匹配
 * @param {String} host
 * @param {String} stub
 * @returns {boolean}
 */
myHelper.hostStubMatch = function (host, stub) {
    return host.toLowerCase().endsWith(stub);
};

/**
 * 构建路径basename
 * @param str
 * @returns {string}
 */
myHelper.baseName = function (str) {
    let base = new String(str).substring(str.lastIndexOf("/") + 1);
    if (base.lastIndexOf(".") != -1) {
        base = base.substring(0, base.lastIndexOf("."));
    }
    return base;
};
myHelper.splitext = function (str) {
    let base = str.substring(str.lastIndexOf("/") + 1);
    let prefix = str.substring(0, str.lastIndexOf("/") + 1);
    let base_name = "";
    let ext_name = "";
    if (base.lastIndexOf(".") != -1) {
        base_name = base.substring(0, base.lastIndexOf("."));
        ext_name = base.substr(base.lastIndexOf("."));
    } else {
        base_name = base;
    }
    return [prefix + base_name, ext_name];
};

myHelper.getUrlQsParam = (url, paramName) => {
    const urlParsed = new Url(url);
    if (urlParsed.query) {
        const qsParsed = qs.parse(
            urlParsed.query.startsWith("?")
                ? urlParsed.query.substring(1)
                : urlParsed.query
        );
        // eslint-disable-next-line no-prototype-builtins
        if (qsParsed && qsParsed.hasOwnProperty(paramName)) {
            return qsParsed[paramName];
        }
    }
    return null;
};
myHelper.getUrlHashParam = (url, paramName) => {
    const urlParsed = new Url(url);
      if (urlParsed.hash) {
        const urlHashStr = urlParsed.hash.startsWith("#")
            ? urlParsed.hash.substring(1)
            : urlParsed.hash;
        const urlHashParsed = new Url(urlHashStr);
        const urlHashParsedQsParsed = qs.parse(
            urlHashParsed.query.startsWith("?")
                ? urlHashParsed.query.substring(1)
                : urlParsed.query
        );
        // eslint-disable-next-line no-prototype-builtins
        if (
            urlHashParsedQsParsed &&
            Object.prototype.hasOwnProperty.call(urlHashParsedQsParsed, paramName)
            // urlHashParsedQsParsed.hasOwnProperty(paramName)
        ) {
            return urlHashParsedQsParsed[paramName];
        }
        const urlHashStrQsParsed = qs.parse(
            urlHashStr.startsWith("/?") || urlHashStr.startsWith("?/")
                ? urlHashStr.substring(2)
                : urlHashStr.startsWith("?") || urlHashStr.startsWith("/")
                    ? urlHashStr.substring(1)
                    : urlHashStr
        );
        // eslint-disable-next-line no-prototype-builtins
        if (urlHashStrQsParsed && urlHashStrQsParsed.hasOwnProperty(paramName)) {
            return urlHashStrQsParsed[paramName];
        }
      }
    return null;
};
myHelper.getUrlQsOrHashParam = (url, paramName) => {
    const urlParsed = new Url(url);
    if (urlParsed.query) {
        const qsParsed = qs.parse(
            urlParsed.query.startsWith("?")
                ? urlParsed.query.substring(1)
                : urlParsed.query
        );
        // eslint-disable-next-line no-prototype-builtins
        if (qsParsed && qsParsed.hasOwnProperty(paramName)) {
            return qsParsed[paramName];
        }
    }
    if (urlParsed.hash) {
        const urlHashStr = urlParsed.hash.startsWith("#")
            ? urlParsed.hash.substring(1)
            : urlParsed.hash;
        const urlHashParsed = new Url(urlHashStr);
        const urlHashParsedQsParsed = qs.parse(
            urlHashParsed.query.startsWith("?")
                ? urlHashParsed.query.substring(1)
                : urlParsed.query
        );
        // eslint-disable-next-line no-prototype-builtins
        if (
            urlHashParsedQsParsed &&
            Object.prototype.hasOwnProperty.call(urlHashParsedQsParsed, paramName)
            // urlHashParsedQsParsed.hasOwnProperty(paramName)
        ) {
            return urlHashParsedQsParsed[paramName];
        }
        const urlHashStrQsParsed = qs.parse(
            urlHashStr.startsWith("/?") || urlHashStr.startsWith("?/")
                ? urlHashStr.substring(2)
                : urlHashStr.startsWith("?") || urlHashStr.startsWith("/")
                    ? urlHashStr.substring(1)
                    : urlHashStr
        );
        // eslint-disable-next-line no-prototype-builtins
        if (urlHashStrQsParsed && urlHashStrQsParsed.hasOwnProperty(paramName)) {
            return urlHashStrQsParsed[paramName];
        }
    }
    return null;
};

export { myHelper };
export default myHelper;
